package ru.dadle8.service.impl.callback.training;

import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.dadle8.model.bot.entity.ContentMessage;
import ru.dadle8.model.bot.entity.MessageCallbackData;
import ru.dadle8.model.bot.entity.State;
import ru.dadle8.model.bot.type.CallbackAction;
import ru.dadle8.service.impl.callback.AbstractCallbackService;

@Service
public class ContinueCallbackServiceImpl extends AbstractCallbackService {

    @Override
    public int getAction() {
        return CallbackAction.CONTINUE.getAction();
    }

    @Override
    public void processUpdate(Update update) throws TelegramApiException {
        State currentState = getStorage().getCurrentState(getChatId());
        if (getContentMessageService().hasNextContentMessage(currentState.menuActionId(), getCallbackData().num())) {
            ContentMessage contentMessage = getContentMessageService().getNextContentMessage(currentState.menuActionId(), getCallbackData().num());

            if (!contentMessage.getVideos().isEmpty()) {
                sendMedia(contentMessage, getChatId());

                MessageCallbackData nextCallbackData = new MessageCallbackData(300, getCallbackData().num() + 1);
                getBot().execute(getMessageHelper().sendMessage(getChatId(), "Упражнение #" + nextCallbackData.num(), getKeyboardService().createInlineMarkup(nextCallbackData)));
                return;
            }
        } else {
            // return to start action
            getStorage().clearState(getChatId());
            getBot().execute(getMessageHelper().sendMessage(getChatId(), "Молодец!"));
        }

        // avoid 'loading...'
        getBot().execute(getMessageHelper().sendAnswerCallbackQuery(getCallbackQuery()));

        // delete current menu message
        getBot().execute(getMessageHelper().sendDeleteMessage(getChatId(), getMessageId()));
    }
}
